#-*- coding:utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from django.http import Http404
from . import forms
from . import models

def fg_list():
    return models.ForumGroup.objects.all()

def login_redirect(urlpath):
    return getattr(settings, 'LOGIN_URL', '/login/')+'?next=%s' % urlpath

def can_edit(user, obj, frm):    
    'verifica permissao de edicao de topico e resposta'
    cls = obj.__class__
    if cls == models.Topic:
        if is_moderator(user, frm):
            return True
    elif cls == models.Reply:
        if is_moderator(user, frm):
            return True
        if frm.allow_reply_edit and (user==obj.author):
            return True
    return False

def can_del(user, obj, frm):    
    'verifica permissao de remocao de topico e resposta'
    if cls == models.Topic:
        if is_moderator(user, frm):
            return True
    elif cls == models.Reply:
        if is_moderator(user, frm):
            return True
        if forum.allow_reply_del and (user==obj.author):
            return True
    return False

def is_moderator(user, forum):
    return user in forum.moderation.all()

def tp_list(user, forum):
    'retorna lista de topicos do forum de acordo com priv. do usuário'
    if is_moderator(user, forum):
        return forum.topic_list.all()
    else: return forum.topic_list.active()

def frm_require_login(request, forum):
    if forum.allow_view_only_to_logged_users and not request.user.is_authenticated():
        return True
    else: return False

def is_following(user, topic):
    if user.is_authenticated():
        flw, created = models.Follow.objects.get_or_create(frm_profile=user.frm_profile, \
                                                       topic=topic)
        return flw.active
    else: return False

def follow(frm_profile, topic, active=None):
    flw, created = models.Follow.objects.get_or_create(frm_profile=frm_profile, \
                                                       topic=topic)
    if active is not None:
        flw.active=active
        flw.save()

def topic_list():
    return models.Topic.objects.active()

def get_forum(pk):
    return get_object_or_404(models.Forum, pk=pk, active=True)

def get_topic(pk, user):
    tp = get_object_or_404(models.Topic, pk=pk)
    frm = tp.forum
    if user.is_authenticated():
        if is_moderator(user, frm):
            return tp, frm

    if tp.active is False:
        raise Http404()
    else: return tp, frm

def get_reply(pk):
    return get_object_or_404(models.Reply, pk=pk, active=True)    

def get_msg(box, pk):
    return get_object_or_404(models.ForumMessage, pk=pk, box=box)

def get_user(pk=None, username=None):
    if any([pk, username]):
        if username is not None:
            return get_object_or_404(User, username=username)
        else: return get_object_or_404(User, pk=pk)
    else: raise Http404('user not found')
